<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace WanZ\App\User\Listener;

use Hyperf\Consul\Exception\ServerException;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BeforeMainServerStart;
use Hyperf\Consul\KV;
use Hyperf\Guzzle\ClientFactory;
use Psr\Container\ContainerInterface;

class ConfigServiceListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @var ClientFactory
     */
    protected $clientFactory;
   

    public function __construct(ContainerInterface $container)
    {
        $this->logger = $container->get(StdoutLoggerInterface::class);
        $this->config = $container->get(ConfigInterface::class);
        $this->clientFactory = $container->get(ClientFactory::class);
    }

    public function listen(): array
    {
        return [
            BeforeMainServerStart::class,
        ];
    }

    /**
     * @param BeforeMainServerStart $event
     */
    public function process(object $event)
    {
        if ($this->config->get('services.enable.register') !== true) {
            throw new \InvalidArgumentException('not enable register');
        }
        
        $consulServer = $this->config->get('services.drivers.consul.uri');
        if (empty($consulServer)) {
            throw new \InvalidArgumentException('Invalid consul uri');
        }
        $token = $this->config->get('services.drivers.consul.token');
        if (empty($token)) {
            throw new \InvalidArgumentException('Invalid consul token');
        }            
        $clientFactory = $this->clientFactory;
        
        $kv = new KV(function () use ($clientFactory, $consulServer) {
            return $clientFactory->create([
                'base_uri' => $consulServer,
            ]);
        });

        $files = explode(',', 'login,jwt');
        foreach ($files as $v) {
            $data = $kv->get('userCenter/'.$v, ['token' => $token])->json();
            $data = array_pop($data);
            if (empty($data)) {
                echo "{$v} is not exists or is empty\n";
                //continue;
                exit;
            }
            $content = "<?php \ndeclare(strict_types=1);\n";
            $value = $content . \base64_decode($data["Value"]);
            $file = BASE_PATH . '/config/autoload/' . $v . '.php';
            file_put_contents($file, $value);        
        }   
    }

}
